import {getRequest, url} from './api'

export const initMenu = (router, store) => {
    return new Promise(resolve => {
        if (store.state.routes.length > 0) {
            resolve(true)
            return
        }
        getRequest(url.getMenuByAdminId.url).then(res => {
            if (res) {
                //Menu菜单存到vuex中
                store.commit('initRoutes', formatRoutes(res.obj))
                //连接websocket
                store.dispatch('connectWS')
                resolve(true)
            } else {
                resolve(false)
            }
        })
    })
}

//包装成Menu菜单
export const formatRoutes = (routes) => {
    let fmtRoutes = []
    routes.forEach(route => {
        let {
            path,
            name,
            iconCls,
            children
        } = route
        if (children && children instanceof Array) {
            //递归
            children = formatRoutes(children)
        }

        let fmtRoute = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children
        }
        fmtRoutes.push(fmtRoute)
    })
    return fmtRoutes
}
